<template>
  <div class="center">
    <div v-if="selectedContact" class="chat-container">
      <!-- 联系人信息头部 -->
      <div class="chat-header">
        <img src="../assets/avator.png" class="header-avatar">
        <div class="header-info">
          <h3>{{ selectedContact.contactId }} ({{ selectedContact.contactPushName }})</h3>
          <span class="status"><UserOutlined />{{ selectedContact.from }} <UserOutlined />{{ selectedContact.contactId }}</span>
        </div>
      </div>
      <!-- 聊天记录区域 -->
      <div class="chat-messages">
        <div v-for="(msg, index) in chatMessages" :key="index"
          :class="['message-bubble', { 'my-message': msg.dr === 0 }]">
          <img v-if="msg.dr === 0" src="../assets/avator.png" class="message-avatar right-avatar">
          <img v-if="msg.dr === 1" src="../assets/avator.png" class="message-avatar left-avatar">
          <div class="message-content">
            <!-- 文本消息 -->
            <div v-if="msg.msgType === 0 || !msg.msgType">
              {{ msg.payload?.text || msg.text }}
              <div v-if="msg.payload?.trText" class="translated-text">{{ msg.payload.trText }}</div>
              <span class="message-status" v-if="msg.dr === 0">
                <LoadingOutlined v-if="msg.status === 'sending'" class="status-icon" />
                <span v-else-if="msg.status === 'sent'" class="status-text">已发送</span>
                <span v-else-if="msg.status === 'failed'" class="status-text failed">发送失败</span>
              </span>
            </div>
            <!-- 图片消息 -->
            <div v-else-if="msg.msgType === 1" class="media-content">
              <Image :src="msg.payload.media" alt="图片消息" style="max-width: 200px; max-height: 200px;" />
            </div>
            <!-- 音频消息 -->
            <div v-else-if="msg.msgType === 2" class="media-content audio-message">
              <div class="audio-player">
                <div class="play-button" @click="playAudio(msg.payload.media)">
                  <i :class="['fas', isPlaying[msg.payload.media] ? 'fa-pause' : 'fa-play']"></i>
                </div>
                <div class="audio-content">
                  <div class="waveform">
                    <div class="wave-pattern">
                      <div v-for="i in 27" :key="i" class="wave-bar"></div>
                    </div>
                  </div>
                  <div class="audio-info">
                    <span class="audio-duration">{{ formatDuration(msg.payload.duration) }}</span>
                    <span v-if="msg.dr === 0" class="message-status">
                      <i class="fas fa-check"></i>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 视频消息 -->
            <div v-else-if="msg.msgType === 3" class="media-content">
              <video controls :src="msg.payload.media" style="max-width: 300px; max-height: 200px;"></video>
            </div>
            <!-- 链接消息 -->
            <div v-else-if="msg.msgType === 4" class="media-content link-message">
              <div class="link-preview">
                <div class="link-title">{{ msg.payload.title || '链接消息' }}</div>
                <div class="link-description">{{ msg.payload.description || msg.payload.text }}</div>
                <a :href="msg.payload.url" target="_blank" class="link-url">{{ msg.payload.url || '查看链接' }}</a>
              </div>
            </div>
            <!-- 名片消息 -->
            <div v-else-if="msg.msgType === 5" class="media-content card-message">
              <div class="contact-card">
                <div class="card-header">
                  <Image src="../assets/avator.png" class="card-avatar" />
                  <div class="card-info">
                    <div class="card-name">{{ msg.payload.name || '联系人' }}</div>
                    <div class="card-phone">{{ msg.payload.phone || msg.payload.text }}</div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 语音通话 -->
            <div v-else-if="msg.msgType === 11" class="media-content call-message">
              <div class="call-info">
                <i class="fas fa-phone"></i>
                <span>语音通话 {{ msg.payload.duration || '' }}</span>
                <span class="call-status">{{ msg.payload.status || '已结束' }}</span>
              </div>
            </div>
            <!-- 视频通话 -->
            <div v-else-if="msg.msgType === 12" class="media-content call-message">
              <div class="call-info">
                <i class="fas fa-video"></i>
                <span>视频通话 {{ msg.payload.duration || '' }}</span>
                <span class="call-status">{{ msg.payload.status || '已结束' }}</span>
              </div>
            </div>
            <!-- 商户超链 -->
            <div v-else-if="msg.msgType === 21" class="media-content business-link">
              <div class="business-preview">
                <div class="business-title">{{ msg.payload.title || '商户信息' }}</div>
                <div class="business-description">{{ msg.payload.description || msg.payload.text }}</div>
                <a :href="msg.payload.url" target="_blank" class="business-url">{{ msg.payload.businessName || '查看商户' }}</a>
              </div>
            </div>
            <!-- 图文超链 -->
            <div v-else-if="msg.msgType === 22" class="media-content image-link">
              <div class="image-link-preview">
                <Image :src="msg.payload.imageUrl || msg.payload.media" alt="图片" class="preview-image" />
                <div class="image-link-content">
                  <div class="image-link-title">{{ msg.payload.title || '图文链接' }}</div>
                  <div class="image-link-description">{{ msg.payload.description || msg.payload.text }}</div>
                  <a :href="msg.payload.url" target="_blank" class="image-link-url">查看详情</a>
                </div>
              </div>
            </div>
            <div class="message-time">{{ msg.time }}</div>
          </div>
        </div>
        
      </div>
      <div class="chat-input">
        <div class="input-wrapper">
          <div class="input-tools">
            <span class="tool-icon"><SmileOutlined /></span>
            <span class="tool-icon"><PaperClipOutlined /></span>
            <span class="tool-icon"><TranslationOutlined /></span>
          </div>
          <a-input v-model:value="messageInput" placeholder="输入消息..." @pressEnter="sendMessage"
            class="message-input" />
          <a-button type="primary" @click="sendMessage" class="send-button">发送</a-button>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import {
  SmileOutlined,
  PaperClipOutlined,
  TranslationOutlined,
  UserOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue';
import { Image } from 'ant-design-vue';  // 修改导入语句
import { useChatStore } from '../stores/chat';

const chatStore = useChatStore();
const selectedContact = computed(() => chatStore.selectedContact);
const chatMessages = computed(() => chatStore.chatMessages);

const messageInput = ref('');
const isPlaying = ref({});

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || !selectedContact.value) return;
  
  const messageText = messageInput.value;
  messageInput.value = ''; // 清空输入框
  
  // 发送消息
  const response = await chatStore.sendMessage(messageText);
  chatStore.scrollToBottom();
  
  // 如果发送成功，更新未读状态
  if (response) {
    // 通过 store 更新消息列表中的已读状态
    const index = chatStore.messageList.findIndex(msg => msg.contactId === selectedContact.value.contactId);
    if (index !== -1) {
      chatStore.messageList[index] = {
        ...chatStore.messageList[index],
        isRead: true,
        unRead: 0
      };
    }
    try {
    await requests.post('/api/externalContacts/unReadCheck', {
      contactId: item.contactId,
      uid: item.uid
    });
    
    // 不再在这里更新消息列表中的已读状态
    // 只保存当前选中的联系人信息，以便后续发送消息时使用
  } catch (error) {
    console.error('未读确认失败:', error);
  }
  }
};

// 格式化音频时长
const formatDuration = (duration) => {
  if (!duration) return '0:00';
  const minutes = Math.floor(duration / 60);
  const seconds = Math.floor(duration % 60);
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};

// 播放音频
const playAudio = (src) => {
  if (!src) return;
  
  if (isPlaying.value[src]) {
    // 如果当前音频正在播放，则暂停
    const audio = document.querySelector(`audio[data-src="${src}"]`);
    if (audio) {
      audio.pause();
      isPlaying.value[src] = false;
    }
    return;
  }
  
  // 创建新的音频元素
  const audio = new Audio(src);
  audio.setAttribute('data-src', src);
  
  // 停止其他正在播放的音频
  Object.keys(isPlaying.value).forEach(key => {
    if (isPlaying.value[key]) {
      const otherAudio = document.querySelector(`audio[data-src="${key}"]`);
      if (otherAudio) {
        otherAudio.pause();
        isPlaying.value[key] = false;
      }
    }
  });
  
  isPlaying.value[src] = true;
  audio.play();
  
  audio.onended = () => {
    isPlaying.value[src] = false;
  };
};
</script>

<style scoped>
.center {
  background-color: #FFF;
  height: 100vh;
  width: 100vw;
  margin-right: 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  position: relative;
}

.chat-header {
  display: flex;
  height: 8%;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.header-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.header-info h3 {
  margin: 0;
  font-size: 16px;
}

.status {
  color: #000000;
  font-size: 12px;
}

.chat-messages {
  padding: 20px;
  height: 80%;
  overflow-y: auto;
  background-color: #e6ded6f2 !important;
  background-image: url('../assets/wsBg.png') !important;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.chat-messages::-webkit-scrollbar {
  display: none;
}

.message-bubble {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  justify-content: flex-start;
}

.message-bubble.my-message {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px;
  border-radius: 8px;
  background: white;
  margin: 0 8px;
  position: relative;
}

.my-message .message-content {
  background: #25d466;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.my-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input {
  display: flex;
  padding: 8px 15px;
  border-top: 1px solid #eee;
  background: white;
  flex-shrink: 0;
  padding-bottom: 100px;
  margin-bottom: 50px;
  box-sizing: border-box;
  align-items: center;
  
}

.input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #f5f5f5;
  border-radius: 16px;
  padding: 0 5px;
  position: relative;
  height: 40px;
}

.input-tools {
  display: flex;
  padding: 0 10px;
}

.tool-icon {
  font-size: 18px;
  color: #666;
  margin-right: 12px;
  cursor: pointer;
  transition: color 0.3s;
  padding: 4px 0;
}

.tool-icon:hover {
  color: #25d466;
}

.message-input {
  flex: 1;
  border: none;
  background-color: transparent;
  box-shadow: none;
}

.message-input :deep(.ant-input) {
  background-color: transparent;
  border: none;
  box-shadow: none;
  padding: 4px 0;
  height: 32px;
}

.send-button {
  background-color: #25d466;
  border-color: #25d466;
  border-radius: 16px;
  height: 32px;
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
  font-size: 14px;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin: 0 8px;
}

.message-avatar.left-avatar {
  margin-right: 8px;
}

.message-avatar.right-avatar {
  margin-left: 8px;
}

/* 音频消息样式 */
.audio-message {
  padding: 8px 12px;
  border-radius: 8px;
  background: #fff;
  max-width: 280px;
  margin: 8px 0;
}

.audio-player {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 160px;
}

.play-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #00a884;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  color: #fff;
  transition: all 0.2s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.play-button i {
  font-size: 16px;
  margin-left: 2px;
}

.audio-content {
  flex: 1;
  min-width: 0;
  padding: 4px 0;
}

.waveform {
  height: 24px;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  padding: 0 8px;
  margin-bottom: 4px;
}

.wave-pattern {
  display: flex;
  align-items: center;
  gap: 1px;
  width: 100%;
  height: 100%;
}

.wave-bar {
  flex: 1;
  background: #8696a0;
  min-height: 2px;
  border-radius: 1px;
  opacity: 0.5;
  transition: height 0.2s;
}

.wave-bar:nth-child(2n) {
  height: 12px;
}

.wave-bar:nth-child(3n) {
  height: 16px;
}

.wave-bar:nth-child(4n) {
  height: 8px;
}
</style>